package com.mulanweb.api.module.controller;

import com.jfinal.core.Controller;
import com.mulanweb.api.module.model.ChatHistory;

import java.util.Date;

/**
 * Created by Administrator on 2016/8/15.
 */
public class ChatHistoryController{

    /**
     * 新增一条聊天记录
     * @param content 聊天内容，或图片url
     * @param type 聊天类型：1为text 2为image
     * @param toUserOpenid 接受者openid
     * @param fromUserOpenid 发送者openid
     * @param createTime 发送时间（时间戳）
     * @return 保存成功或失败
     */
    synchronized public static Boolean save(String content, String type, String toUserOpenid, String fromUserOpenid, Long createTime){
        if(dateRepeat(fromUserOpenid,toUserOpenid, createTime)){
            ChatHistory chatHistory = new ChatHistory();
            chatHistory.setContent(content);
            chatHistory.setChatType(type);
            chatHistory.setToUserOpenid(toUserOpenid);
            chatHistory.setFromUseropenId(fromUserOpenid);
            chatHistory.setSent_time(createTime);
            chatHistory.setCreate_time(new Date());
            return chatHistory.save();
        }
        return false ;
    }

    /**
     * 聊天记录排重
     * @param fromUserOpenid 发送者openid
     * @param sentTime 发送时间（时间戳）
     * @return 存在返回 true
     */
    synchronized public  static Boolean dateRepeat(String fromUserOpenid,String touseropenid, Long sentTime){
        ChatHistory chatHistory = ChatHistory.dao.findFirst("SELECT * FROM chat_history WHERE from_user_openid = ? and to_user_openid = ? and sent_time = ?", fromUserOpenid,touseropenid, sentTime);
        if(chatHistory != null && chatHistory.getId() >0){
            return false ;
        }
        return true;
    }
}
